package com.cl.ks.controller;

import com.alibaba.fastjson.JSONObject;
import com.cl.ks.entity.KsFilter;
import com.cl.ks.service.AutoFilterService;
import com.cl.ks.service.FilterAsyncService;
import com.cl.ks.service.FilterService;
import com.cl.ks.utils.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;

/**
 * @author chenyitao
 * @date 2021/4/19
 */
@RestController
@RequestMapping("/filter")
@CrossOrigin
@Api(tags = "提取任务接口")
public class FilterController {
    private final FilterService filterService;
    private final AutoFilterService autoFilterService;


    public FilterController(FilterService filterService, AutoFilterService autoFilterService) {
        this.filterService = filterService;
        this.autoFilterService = autoFilterService;
    }


    @RequestMapping(path = "/examFilter", method = RequestMethod.GET)
    public CommonResult<List<String>> examFilter(@RequestParam(name = "filterId") Integer filterId) {
        return CommonResult.success(filterService.examFilter(filterId));
    }

    @RequestMapping(path = "/getProgress", method = RequestMethod.GET)
    public FilterAsyncService.FilterProgress getProgress(@RequestParam(name = "filterId") Integer filterId) {
        return filterService.getProgress(filterId);
    }

    @RequestMapping(path = "/initPosition", method = RequestMethod.GET)
    public ResponseEntity<Object> initLastPosition() {
        autoFilterService.initLastPosition();
        return ResponseEntity.ok().body("SUCCESS");
    }

    @ApiOperation("手动执行定时提取任务增量提取")
    @RequestMapping(path = "/autoUpdate", method = RequestMethod.GET)
    public ResponseEntity<Object> autoUpdate() {
        autoFilterService.autoUpdate();
        return ResponseEntity.ok().body("SUCCESS");
    }

    @ApiOperation("新增提取任务")
    @RequestMapping(path = "/new", method = RequestMethod.POST)
    public ResponseEntity<Object> newFilterTask(@RequestHeader(name = "Authorization", defaultValue = "") String auth, @RequestBody FilterService.FilterBundle filterBundle) {
        filterBundle.setAuth(auth);
        return filterService.newFilterTask(filterBundle);
    }

    @ApiOperation("编辑提取任务")
    @RequestMapping(path = "/update", method = RequestMethod.POST)
    public ResponseEntity<Object> updateFilterTask(@RequestHeader(name = "Authorization", defaultValue = "") String auth, @RequestBody FilterService.FilterBundle filterBundle) {
        return filterService.updateFilterTask(auth, filterBundle);
    }

    @ApiOperation("更改提取任务状态")
    @RequestMapping(path = "/edit", method = RequestMethod.POST)
    public ResponseEntity<Object> editFilterTask(@RequestBody FilterService.FilterBundle filterBundle) {
        return filterService.editFilterTask(filterBundle);
    }


    @ApiOperation("提交提取任务（用于任务列表）")
    @RequestMapping(path = "/executeFilterTask", method = RequestMethod.POST)
    public ResponseEntity<Object> executeFilterTask(@RequestBody JSONObject param) {
        Integer id = param.getInteger("id");
        return filterService.rerunFilterTask(id, param);
    }

    @ApiOperation("提取任务重新提取")
    @RequestMapping(path = "/rerun", method = RequestMethod.GET)
    public ResponseEntity<Object> rerunFilterTask(@RequestParam(name = "id") Integer recordId) {
        return filterService.rerunFilterTask(recordId, null);
    }

    @ApiOperation("批量重提提取任务")
    @RequestMapping(path = "/rerunFilters", method = RequestMethod.GET)
    public ResponseEntity<Object> createFilters(@RequestHeader(name = "Authorization", defaultValue = "") String auth, String filterIds) {
        String msg = "over ";
        for (String filterId : filterIds.split(",")) {
            try {
                filterService.rerunFilterTask(Integer.valueOf(filterId), null);
            } catch (Exception e) {
                e.printStackTrace();
                msg += e.getMessage() + " \n ";
            }
        }
        return ResponseEntity.ok().body(msg);
    }

    @ApiOperation("所有提取任务重新提取")
    @RequestMapping(path = "/rerunAll", method = RequestMethod.GET)
    public ResponseEntity<Object> rerunAll() {

        return filterService.rerunAll();
    }

    @ApiOperation("线索表全部重跑")
    @RequestMapping(path = "/clueAutoResult", method = RequestMethod.GET)
    public ResponseEntity<Object> clueAutoResult() {
        filterService.clueAutoResult(null);
        return null;
    }

    @ApiOperation("删除提取任务")
    @RequestMapping(path = "/delete", method = RequestMethod.GET)
    public ResponseEntity<Object> deleteFilterRecord(@RequestParam(name = "id") Integer recordId) {
        return filterService.deleteFilterRecord(recordId);
    }

    @ApiOperation("提取任务列表")
    @RequestMapping(path = "/list", method = RequestMethod.POST)
    public ResponseEntity<Object> filterTaskList(@RequestHeader(name = "Authorization", defaultValue = "") String auth, @RequestBody Map<String, Object> param) {
        return filterService.filterTaskList(auth, param);
    }


    @ApiOperation("查看提取结果")
    @RequestMapping(path = "/result", method = RequestMethod.POST)
    public ResponseEntity<Object> filterTaskDetail(@RequestBody Map<String, Object> param) {
        return filterService.filterTaskDetail(param);
    }

    @ApiOperation("修改提取结果有效状态")
    @GetMapping("/updateFilterResultAvailable")
    public ResponseEntity updateFilterResultAvailable(Integer resultId, Integer available) {
        return filterService.updateFilterResultAvailable(resultId, available);
    }

    @ApiOperation("提取结果文件下载")
    @RequestMapping(path = "/download", method = RequestMethod.GET)
    public ResponseEntity downloadFilterResult(@RequestParam(name = "id") Integer id, HttpServletResponse httpServletResponse) {
        filterService.getFilterFile(id, httpServletResponse);
        return ResponseEntity.ok("");

    }

    @ApiOperation("增量提取结果文件下载")
    @RequestMapping(path = "/download/increment", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> downloadIncrementFilterResult(@RequestParam(name = "id") String id) throws FileNotFoundException {
        File excelFile = filterService.getIncrementFilterFile(id);
        if (excelFile != null && excelFile.exists()) {
            return ResponseEntity.ok()
                    .header("content-disposition", "attachment; filename=" + excelFile.getName())
                    .contentLength(excelFile.length())
                    .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    .body(new InputStreamResource(new FileInputStream(excelFile)));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @ApiOperation("更新配置")
    @GetMapping(path = "/updateConfigure")
    public ResponseEntity<Object> updateConfigure(@RequestParam("tableName") String tableName,
                                                  @RequestParam("value") Integer value) {
        return filterService.updateConfigure(tableName, value);
    }

    @ApiOperation("通过提取任务id查询提取任务执行记录")
    @PostMapping(path = "/listFilterLog")
    public ResponseEntity<Object> listFilterLog(KsFilter ksFilter) {
        return filterService.listFilterLog(ksFilter);
    }

    @ApiOperation("通过规则id分页查询提取任务执行记录")
    @PostMapping("listFilterLogByRuleId")
    public ResponseEntity listFilterLogByRuleId(@RequestBody Map<String, Object> param) {
        return filterService.listFilterLogByRuleId(param);
    }

    @ApiOperation("通过规则标签查询提取任务执行记录")
    @PostMapping("listFilterLogByRuleType")
    public ResponseEntity listFilterLogByRuleType(@RequestBody Map<String, Object> param) {
        return filterService.listFilterLogByRuleType(param);
    }


    @ApiOperation("通过规则id查询提取任务执行记录")
    @GetMapping("listFilterLogByRuleId")
    public ResponseEntity listFilterLogByRuleId(@RequestParam("ruleId") Integer ruleId) {
        return filterService.listFilterLogByRuleId(ruleId);
    }

    @ApiOperation("提取任务执行情况统计")
    @GetMapping("listFilterStatisticsByRuleId")
    public ResponseEntity listFilterStatisticsByRuleId(@RequestParam("ruleId") Integer ruleId) {
        return filterService.listFilterStatisticsByRuleId(ruleId);
    }

    @ApiOperation("查询提取结果")
    @PostMapping("listFilterResult")
    public ResponseEntity listFilterResultByArea(String startDate, String endDate) {
        return filterService.listFilterResultByArea(startDate, endDate);
    }

    @ApiOperation("人物关系echarts折线图接口")
    @GetMapping("supervisePersonRelationEchartsSeries")
    public ResponseEntity supervisePersonRelationEchartsSeries(String name, String idCard, String dbCode) {
        return filterService.supervisePersonRelation(name, idCard, dbCode);
    }

    @ApiOperation("通过规则类型查询提取记录")
    @GetMapping("listFilterLogByRuleType")
    public ResponseEntity listFilterLogByRuleType(String ruleType) {
        return filterService.listFilterLogByRuleType(ruleType);
    }

    @ApiOperation("通过提取结果id查询源数据")
    @GetMapping("/getSourceDataByFilterResultId")
    public ResponseEntity getSourceDataByResultId(Integer filterResultId) {
        return filterService.getSourceDataByFilterResultId(filterResultId);
    }
}
